<?php

declare(strict_types=1);

namespace App\Middleware;

use App\Exception\SessionValidException;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Hyperf\Contract\SessionInterface;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Utils\Context;

class AdminAuthMiddleware implements MiddlewareInterface
{
    /**
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @var SessionInterface
     */
    protected $session;

    /**
     * @var RequestInterface
     */
    protected $httpRequest;

    public function __construct(ContainerInterface $container,SessionInterface $session,RequestInterface $httpRequest)
    {
        $this->container = $container;
        $this->session = $session;
        $this->httpRequest = $httpRequest;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        if($this->httpRequest->getPathInfo()!='/admin/login'){
            if(!$this->session->has('admin')||!$this->session->get('admin',null)){
                throw new SessionValidException('还未登录', 401);
            }
        }
        $request = Context::set(ServerRequestInterface::class, $request->withAttribute('admin', '123'));
        return $handler->handle($request);
    }
}